<template>
  <div class="detail">
    <nav-bar title="商品详情" :isBack="true"></nav-bar>
    <van-swipe class="my-swipe" :autoplay="3000" indicator-color="red">
      <van-swipe-item v-for="(item, index) in detail.pics" :key="item.goods_id">
        <img :src="item.pics_big" alt="" @click="lookBig(index)">
      </van-swipe-item>
    </van-swipe>
    <h5>
      ￥{{ detail.goods_price }}
    </h5>
    <section class="title">{{ detail.goods_name }}</section>
    <div v-html="detail.goods_introduce"></div>
    <van-action-bar>
      <van-action-bar-icon icon="chat-o" text="客服" color="#ee0a24" />
      <van-action-bar-icon icon="cart-o" text="购物车" @click="$router.push('/cart')" />
      <van-action-bar-icon icon="star-o" text="收藏" color="#ff5000" />
      <van-action-bar-button type="warning" text="加入购物车" @click="addCart" />
      <van-action-bar-button type="danger" text="立即购买" />
    </van-action-bar>

  </div>
</template>
<script>
import { getDetail } from '@/api/other/index';
import { showImagePreview, showNotify } from 'vant'; // 引入图片预览
// import { showNotify } from 'vant'; // 消息通知
export default {
  data() {
    return {
      detail: {}, // 详情的对象
    }
  },
  created() {
    let goodId = this.$route.params.id; // 动态路由传入的参数
    getDetail({ goods_id: goodId }).then(res => { // 详情的数据请求
      this.detail = res.message;
    })
  },
  methods: {
    lookBig(i) {  // 查看大图
      let imgs = this.detail.pics.map(item => item.pics_big);
      // console.log(imgs);
      showImagePreview({
        images: imgs, // images 是所有的图片
        startPosition: i, // 初始位置
      });
    },
    addCart() { // 加入购物车
      let token = localStorage.getItem('token');
      if (!token) {
        this.$router.push('/login')
      } else {
        let obj = {
          name: this.detail.goods_name, // 商品名称
          price: this.detail.goods_price, // 商品价格
          img: this.detail.goods_small_logo, // 商品图片
          buyNum: 1, // 购买数量
          flag: false, // 购物车数据的选中状态
          id: this.detail.goods_id // 商品的id
        }
        this.$store.commit('saveCart', obj);
        showNotify({ type: 'success', message: '已加入' })
      }
    }
  }
}
</script>
<style lang="scss" scoped>
.detail {
  height: 100%;

  .my-swipe {
    img {
      width: 100%;
      display: block;
    }
  }

  h5 {
    color: red;
    background-color: #fff;
    line-height: 40px;
  }

  .title {
    font-size: 15px;
    background-color: #fff;
    padding: 10px;
    box-sizing: border-box;
  }
}
</style>